<template>
  <div class="message-management">
    <!-- 顶部导航 -->
    <el-page-header @back="handleBack" content="消息管理"></el-page-header>

    <!-- 消息统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card>
          <div class="stats-card">
            <p>全部消息</p>
            <h3>{{ totalMessages }}</h3>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="stats-card">
            <p>未读消息</p>
            <h3 class="unread-count">{{ unreadCount }}</h3>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 主内容区 -->
    <el-row :gutter="20" class="main-content">
      <!-- 左侧对话列表 -->
      <el-col :span="6">
        <el-card class="conversation-card">
          <div class="conversation-list-header">
            <el-input
                placeholder="搜索对话"
                v-model="searchKeyword"
                prefix-icon="Search"
                size="small"
            ></el-input>
          </div>

          <div class="conversation-list">
            <el-scrollbar height="100%">
              <div
                  v-for="conversation in filteredConversations"
                  :key="conversation.message.id"
                  class="conversation-item"
                  :class="{ 'active': activeConversationId === conversation.message.id }"
                  @click="handleSelectConversation(conversation)"
              >
                <div class="avatar">
                  <el-avatar :icon="User"></el-avatar>
                </div>
                <div class="conversation-info">
                  <div class="conversation-title">
                    <span>{{ conversation.receiverName }}</span>
                    <span class="time">{{ formatTime(conversation.message.updatedAt) }}</span>
                  </div>
                  <div class="last-message">{{ conversation.message.content }}</div>
                </div>
                <div v-if="conversation.unreadCount > 0" class="unread-badge">
                  <el-badge :value="conversation.unreadCount" type="danger" />
                </div>
              </div>
            </el-scrollbar>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧消息详情 -->
      <el-col :span="18">
        <el-card v-if="activeConversation" class="message-detail-card">
          <!-- 消息头部 -->
          <div class="message-header">
            <h3>{{ activeConversation.receiverName }}</h3>
            <el-button
                type="text"
                @click="handleMarkConversationAsRead"
                size="small"
            >
              标记全部为已读
            </el-button>
          </div>

          <!-- 消息内容区 -->
          <div class="message-content">
            <el-scrollbar height="100%">
              <!-- 先显示主消息 -->
              <div class="message-item">
                <div :class="getMessageClass(activeConversation.message)">
                  <el-avatar :icon="User" class="msg-avatar"></el-avatar>
                  <div class="msg-bubble">
                    <p>{{ activeConversation.message.content }}</p>
                    <span class="msg-time">{{ formatTime(activeConversation.message.createdAt) }}</span>
                    <el-tag
                        v-if="activeConversation.message.status === 0 && activeConversation.message.receiverId === currentUser.id"
                        size="small"
                        type="info"
                        @click="handleMarkAsRead(activeConversation.message.id)"
                    >
                      未读
                    </el-tag>
                  </div>
                </div>
              </div>

              <!-- 然后显示回复消息 -->
              <div v-for="msg in activeConversation.message.replies" :key="msg.id" class="message-item">
                <div :class="getMessageClass(msg)">
                  <el-avatar :icon="User" class="msg-avatar"></el-avatar>
                  <div class="msg-bubble">
                    <p>{{ msg.content }}</p>
                    <span class="msg-time">{{ formatTime(msg.createdAt) }}</span>
                    <el-tag
                        v-if="msg.status === 0 && msg.receiverId === currentUser.id"
                        size="small"
                        type="info"
                        @click="handleMarkAsRead(msg.id)"
                    >
                      未读
                    </el-tag>
                  </div>
                </div>
              </div>
            </el-scrollbar>
          </div>

          <!-- 消息输入区 - 仅商家可见 -->
          <div v-if="isMerchant" class="message-input">
            <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入回复内容..."
                v-model="replyContent"
                @keyup.enter.native="handleSendReply"
            ></el-input>
            <div class="reply-actions">
              <el-button
                  type="primary"
                  @click="handleSendReply"
                  :disabled="!replyContent.trim()"
              >
                发送回复
              </el-button>
              <span class="reply-hint">按Enter键发送</span>
            </div>
          </div>

          <!-- 管理员提示 - 仅管理员可见 -->
          <div v-else class="admin-hint">
            <el-divider content-position="left">权限说明</el-divider>
            <p>管理员账号仅可查看消息，无法进行回复操作。</p>
          </div>
        </el-card>

        <div v-else class="no-conversation">
          <p>请选择一个对话查看详情</p>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
// 脚本部分保持不变
import {ref, onMounted, computed} from 'vue';
import { User, Search } from '@element-plus/icons-vue';
import { ElMessage, ElDivider } from 'element-plus';
import request from '@/utils/request';
import { format } from 'date-fns';

// 用户信息获取
const userInfo = ref(JSON.parse(localStorage.getItem('backUser') || '{}'))
const currentUser = ref({
  id: userInfo.value.id,
  role: userInfo.value.role
});

// 判断是否为商家
const isMerchant = computed(() => {
  return currentUser.value.role === 'MERCHANT';
});

// 判断是否为管理员
const isAdmin = computed(() => {
  return currentUser.value.role === 'ADMIN'|| currentUser.value.role === 'SUPER_ADMIN';
});

// 状态管理
const conversations = ref([]);
const activeConversation = ref(null);
const activeConversationId = ref(null);
const unreadCount = ref(0);
const totalMessages = ref(0);
const searchKeyword = ref('');
const replyContent = ref('');

// 生命周期钩子
onMounted(() => {
  // 确保用户信息存在再获取对话列表
  if (userInfo.value && userInfo.value.id) {
    fetchConversations();
    fetchUnreadCount();
    fetchTotalMessages();
  } else {
    ElMessage.error('用户信息不存在，请重新登录');
  }
});

// API调用函数
const fetchConversations = async () => {
  try {
    const userId = userInfo.value.id
    if (!userId) {
      ElMessage.error('用户ID不存在');
      return;
    }

    const response = await request.get(`/message/conversations/${userId}`, {
      params: { userRole: userInfo.value.role }
    });

    if (response.code === '0') {
      conversations.value = response.data || [];
      // 默认选中第一个对话
      if (conversations.value.length > 0) {
        handleSelectConversation(conversations.value[0]);
      }
    } else {
      ElMessage.error('获取对话列表失败');
    }
  } catch (error) {
    console.error('获取对话列表出错:', error);
    ElMessage.error('获取对话列表失败');
  }
};

const fetchUnreadCount = async () => {
  try {
    const userId = userInfo.value.id
    const response = await request.get(`/message/unread/count/${userId}`, {
      params: { userRole: userInfo.value.role }
    });
    if (response.code === '0') {
      unreadCount.value = response.data || 0;
    }
  } catch (error) {
    console.error('获取未读消息数出错:', error);
  }
};
// 获取总消息数
const fetchTotalMessages = async () => {
  try {
    const response = await request.get(`/message/page`, {
      params: {
        userId: userInfo.value.id,
        currentPage: 1,
        size: 1,
        userRole: userInfo.value.role
      }
    });
    if (response.code === '0') {
      totalMessages.value = response.data?.total || 0;
    }
  } catch (error) {
    console.error('获取总消息数出错:', error);
  }
};

const fetchConversationDetail = async (conversationId) => {
  try {
    const response = await request.get(`/message/conversation/${conversationId}`, {
      params: {
        currentUserId: userInfo.value.id,
        userRole: userInfo.value.role
      }
    });

    if (response.code === '0') {

      return response.data;

    } else {
      ElMessage.error('获取对话详情失败');
      return null;
    }

  } catch (error) {
    console.error('获取对话详情出错:', error);
    ElMessage.error('获取对话详情失败');
    return null;
  }
};

// 事件处理函数
const handleSelectConversation = async (conversation) => {
  activeConversationId.value = conversation.message.id;
  const detail = await fetchConversationDetail(conversation.message.id);
  if (detail) {
    activeConversation.value = {
      ...conversation,
      message: detail
    };
    // 如果有未读消息，自动标记为已读
    if (conversation.unreadCount > 0) {
      await handleMarkConversationAsRead();
    }
  }
};

const handleMarkAsRead = async (messageId) => {
  try {
    const response = await request.put(`/message/read/${messageId}`, null, {
      params: {
        currentUserId: userInfo.value.id,
        userRole: userInfo.value.role
      }
    });
    if (response.code === '0') {
      ElMessage.success('已标记为已读');
      // 更新本地状态
      updateMessageStatus(messageId, 1);
      await fetchUnreadCount();
      await fetchTotalMessages();
      await fetchConversations();

    } else {
      ElMessage.error(response.msg || '标记失败');
    }
  } catch (error) {
    console.error('标记消息为已读出错:', error);
    ElMessage.error('标记失败');
  }
};

const handleMarkConversationAsRead = async () => {
  if (!activeConversationId.value) return;

  try {
    const response = await request.put(`/message/conversation/read/${activeConversationId.value}`, null, {
      params: {
        userId: userInfo.value.id,
        userRole: userInfo.value.role
      }
    });
    if (response.code === '0') {
      ElMessage.success('整个对话已标记为已读');
      // 更新本地状态
      if (activeConversation.value) {
        activeConversation.value.unreadCount = 0;
      }
      fetchConversations();
      fetchUnreadCount();
      fetchTotalMessages();
    } else {
      ElMessage.error(response.msg || '标记失败');
    }
  } catch (error) {
    console.error('标记对话为已读出错:', error);
    ElMessage.error('标记失败');
  }
};

const handleSendReply = async () => {
  // 权限检查：只有商家可以发送回复
  if (!isMerchant.value) {
    ElMessage.warning('管理员账号无法回复消息');
    return;
  }

  if (!replyContent.value.trim() || !activeConversationId.value) return;

  try {
    const response = await request.post('/message/reply', {
      conversationId: activeConversationId.value,
      parentId: activeConversationId.value,
      senderId: userInfo.value.id,
      receiverId: activeConversation.value.message.senderId === userInfo.value.id
          ? activeConversation.value.message.receiverId
          : activeConversation.value.message.senderId,
      content: replyContent.value,
      messageType: 0
    });

    if (response.code === '0') {
      ElMessage.success('回复发送成功');
      replyContent.value = '';
      // 重新获取对话详情
      const detail = await fetchConversationDetail(activeConversationId.value);
      if (detail) {
        activeConversation.value.message = detail;
      }
      fetchConversations();
      fetchUnreadCount();
      fetchTotalMessages();
    } else {
      ElMessage.error(response.msg || '发送失败');
    }
  } catch (error) {
    console.error('发送回复出错:', error);
    ElMessage.error('发送失败');
  }
};

const handleBack = () => {
  window.history.back();
};

// 辅助函数
const formatTime = (timestamp) => {
  if (!timestamp) return '';
  return format(new Date(timestamp), 'yyyy-MM-dd HH:mm');
};

const updateMessageStatus = (messageId, status) => {
  if (activeConversation.value && activeConversation.value.message) {
    // 更新主消息状态
    if (activeConversation.value.message.id === messageId) {
      activeConversation.value.message.status = status;
    }
    // 更新回复消息状态
    if (activeConversation.value.message.replies && Array.isArray(activeConversation.value.message.replies)) {
      const replyIndex = activeConversation.value.message.replies.findIndex(reply => reply.id === messageId);
      if (replyIndex !== -1) {
        activeConversation.value.message.replies[replyIndex].status = status;
      }
    }
    // 更新对话列表中的未读计数
    if (Array.isArray(conversations.value)) {
      const convIndex = conversations.value.findIndex(
          conv => conv.message && conv.message.id === activeConversationId.value
      );
      if (convIndex !== -1 && conversations.value[convIndex].unreadCount > 0) {
        conversations.value[convIndex].unreadCount = Math.max(0, conversations.value[convIndex].unreadCount - 1);
      }
    }
  }
};

// 搜索过滤后的对话列表
const filteredConversations = computed(() => {
  if (!searchKeyword.value) return conversations.value;
  const keyword = searchKeyword.value.toLowerCase();
  if (!Array.isArray(conversations.value)) {
    return [];
  }
  return conversations.value.filter(conv =>
      (conv.receiverName && conv.receiverName.toLowerCase().includes(keyword)) ||
      (conv.message && conv.message.content && conv.message.content.toLowerCase().includes(keyword))
  );
});

// 根据消息发送者身份确定消息显示位置
const getMessageClass = (message) => {
  // 如果是管理员查看消息
  if (isAdmin.value) {
    // 如果消息发送者是用户(MERCHANT以外的角色)，则显示在右边
    if (message.senderRole !== 'MERCHANT') {
      return 'sent';
    } else {
      // 如果消息发送者是商家，则显示在左边
      return 'received';
    }
  }
  // 如果是商家查看消息
  else if (isMerchant.value) {
    // 商家自己发送的消息显示在右边
    if (message.senderId === currentUser.value.id) {
      return 'sent';
    } else {
      // 用户发送的消息显示在左边
      return 'received';
    }
  }
  // 其他情况（用户查看消息）
  else {
    // 自己发送的消息显示在右边
    if (message.senderId === currentUser.value.id) {
      return 'sent';
    } else {
      // 商家发送的消息显示在左边
      return 'received';
    }
  }
};
</script>

<style scoped>
.message-management {
  padding: 20px;
  box-sizing: border-box;
  min-height: 100vh;
}

.stats-row {
  margin: 20px 0;
}

.stats-card {
  text-align: center;
  padding: 15px 0;
}

.stats-card p {
  color: #666;
  margin-bottom: 10px;
}

.stats-card h3 {
  font-size: 24px;
  margin: 0;
}

.unread-count {
  color: #f56c6c;
}

.main-content {
  margin-top: 20px;
  height: calc(100vh - 220px); /* 调整主内容区高度 */
}

/* 左侧对话卡片 */
.conversation-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.conversation-list-header {
  padding: 10px 15px;
  border-bottom: 1px solid #eee;
}

.conversation-list {
  padding: 10px 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.conversation-item {
  padding: 12px 15px;
  cursor: pointer;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f5f5f5;
  transition: background-color 0.2s;
}

.conversation-item:hover {
  background-color: #f5f5f5;
}

.conversation-item.active {
  background-color: #e6f7ff;
}

.avatar {
  margin-right: 12px;
}

.conversation-info {
  flex: 1;
  overflow: hidden;
}

.conversation-title {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.conversation-title span:first-child {
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 70%;
}

.time {
  font-size: 12px;
  color: #999;
}

.last-message {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.unread-badge {
  margin-left: 5px;
}

/* 右侧消息详情卡片 */
.message-detail-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.message-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-content {
  flex: 1;
  padding: 20px;
  overflow: hidden;
  min-height: 0; /* 解决flex子元素最小高度问题 */
}

.message-item {
  margin-bottom: 20px;
}

.message-item .sent,
.message-item .received {
  display: flex;
  align-items: flex-end;
}

.message-item .sent {
  flex-direction: row-reverse;
}

.msg-avatar {
  margin: 0 10px;
}

.msg-bubble {
  max-width: 60%;
  padding: 10px 15px;
  border-radius: 8px;
  position: relative;
}

.sent .msg-bubble {
  background-color: #409eff;
  color: white;
}

.received .msg-bubble {
  background-color: #f5f5f5;
  color: #333;
}

.msg-time {
  font-size: 12px;
  margin-top: 5px;
  display: inline-block;
  opacity: 0.8;
}

/* 消息输入区 */
.message-input {
  padding: 15px;
  border-top: 1px solid #eee;
  box-sizing: border-box;
}

.message-input .el-input {
  margin-bottom: 10px;
}

.reply-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
}

.reply-hint {
  color: #999;
  font-size: 12px;
}

.admin-hint {
  padding: 15px;
  border-top: 1px solid #eee;
  color: #666;
  background-color: #fafafa;
  font-size: 14px;
}

.no-conversation {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  background-color: #fafafa;
  border-radius: 4px;
}

/* 确保输入框不会无限扩展 */
.el-textarea__inner {
  resize: vertical;
  max-height: 200px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .msg-bubble {
    max-width: 70%;
  }
}

@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
    height: auto;
  }

  .el-col {
    width: 100% !important;
  }

  .conversation-card, .message-detail-card {
    height: auto;
    margin-bottom: 20px;
  }

  .conversation-list {
    max-height: 300px;
  }

  .message-content {
    max-height: 400px;
  }
}
</style>
